package com.woyou.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import com.woyou.Constant;
import com.woyou.bean.Info;
import com.woyou.bean.rpc.MD5Req;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

/**
 * 封装常用方法的工具类
 * 
 * @author longtao.li
 * 
 */
public class Utils {

	private static final String PICASSO_CACHE = "picasso-cache";

	/**
	 * 判断app是否在后台运行
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isBackgroundRunning(Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * weburl加密拼接封装
	 * 
	 * @param url
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("rawtypes")
	public static String getWebUrl(String url, MD5Req req)
			throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder();
		sb.append(url).append("?params=")
				.append(URLEncoder.encode(req.jsonParams, "UTF-8"))
				.append("&isEncrypted=").append(req.isEncrypted)
				.append("&timeStamp=").append(req.timeStamp)
				.append("&randomNum=").append(req.randomNum).append("&sign=")
				.append(req.sign);
		return sb.toString();
	}

	public static File createDefaultCacheDir(Context context) {
		File cache = new File(context.getApplicationContext().getCacheDir(),PICASSO_CACHE);
		if (!cache.exists()) {
			cache.mkdirs();
		}
		return cache;
	}
	
	@SuppressWarnings("rawtypes")
	public static void openActivity(Context context, Class clazz, final Info info) {

				Intent intent = new Intent();
				intent.setClass(context, clazz);
				if (info != null) {
					intent.putExtra(Constant.INFO_NAME, info);
				}
				context.startActivity(intent);

	}
	

}
